<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Rate extends CI_Controller {
    function Rate() {
        parent::__construct();
	$this->load->helper('html');
	$this->load->helper('url');
	$this->load->helper('form');
    }
    
    public function submit(){        
        $car_id = $this->input->post('car_id');
        if($car_id)
        {
            $this->load->model('Car_model');
            $car_list = $this->Car_model->get_car_by_id($car_id);
            if($car_list->num_rows != 0)
            {
                foreach($car_list->result() as $row)
                {
                    $widget_id = $this->input->post('widget_id');
                    $number_vote = $row->number_votes;
                    $total_point = $row->total_points;
                    $dec_avg = $number_vote == 0 ? 0 : round($total_point / $number_vote, 1 );
                    $whole_avg = round($dec_avg);

                    $data['number_votes'] = $number_vote;
                    $data['total_points'] = $total_point;
                    $data['dec_avg'] = $dec_avg;
                    $data['whole_avg'] = $whole_avg;

                    $clicked_on = $this->input->post('clicked_on');
                    if($clicked_on)
                    {
                        //Get the value of the vote
                        preg_match('/star_([1-5]{1})/', $clicked_on, $match);
                        $vote = $match[1];

                        $number_vote = $row->number_votes + 1;                        
                        $total_point = $row->total_points + $vote;

                        $dec_avg = round($total_point / $number_vote, 1 );
                        $whole_avg = round($dec_avg);

                        $data = array(
                            'number_votes' => $number_vote ,
                            'total_points' => $total_point ,
                            'dec_avg' => $dec_avg,
                            'whole_avg' => $whole_avg
                        );

                        $this->db->where('id', $car_id);
                        $this->db->update('psacar_car', $data);
                    }
                    
                    echo json_encode($data);
                }               
            }            	            
        }	          
    }
}